package com.avocado.configuration.validator;


import com.avocado.configuration.repository.SequenceRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Slf4j
public class SequenceEditNameValidator implements ConstraintValidator<SequenceEditNameValidation, Object> {
    private String field1;
    private String field2;

    private final SequenceRepository sequenceRepository;

    public SequenceEditNameValidator(SequenceRepository sequenceRepository) {
        this.sequenceRepository = sequenceRepository;
    }

    @Override
    public void initialize(SequenceEditNameValidation constraintAnnotation) {
        this.field1 = constraintAnnotation.field1();
        this.field2 = constraintAnnotation.field2();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {


        try {

            Object field1Value = PropertyUtils.getProperty(value, field1);

            Object field2Value = PropertyUtils.getProperty(value, field2);

            Long id=(Long)field1Value;

            String name=(String)field2Value;

            long count=sequenceRepository.getCountByNameAndExcludeId(name,id);

            return count<1L;

        } catch (Exception ex) {

            log.error(ex.getLocalizedMessage());

        }
        return false;
    }
}
